"""
模块名称: example_tcpclient.py
作者: Lysander.Li
创建时间: 2025 - 11 - 05
最后修改时间: 2025 - 11 - 05
功能描述: TCP客户端连接示例程序
"""

# 导入usocket模块
# -*- coding: UTF-8 -*-
import usocket
import log


class TCPClient:
    """TCP客户端封装类"""
    
    def __init__(self, host, port):
        """初始化TCP客户端
        Args:
            host (str): 服务器地址
            port (int): 服务器端口
        """
        self.host = host
        self.port = port
        self.sock = None
        self.logger = log.getLogger("TCP_CLIENT")
        
    def connect(self):
        """建立TCP连接"""
        sockaddr = usocket.getaddrinfo(self.host, self.port)[0][-1]
        self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
        self.sock.connect(sockaddr)
        self.logger.info("Connected to {}:{}".format(self.host, self.port))
        
    def send(self, data):
        """发送数据到服务器
        Args:
            data (str): 要发送的字符串数据
        Returns:
            int: 发送的字节数
        """
        if isinstance(data, str):
            data = data.encode()
        return self.sock.send(data)
        
    def recv(self, bufsize=1024):
        """从服务器接收数据
        Args:
            bufsize (int): 接收缓冲区大小
        Returns:
            bytes: 接收到的数据
        """
        return self.sock.recv(bufsize)
        
    def close(self):
        """关闭TCP连接"""
        if self.sock:
            self.sock.close()
            self.sock = None
            self.logger.info("Connection closed")


# 使用示例
if __name__ == '__main__':
    # 设置日志级别
    log.basicConfig(level=log.INFO)
    
    # 创建并使用TCP客户端
    client = TCPClient('101.37.104.185', 44215)
    client.connect()
    
    # 发送消息
    bytes_sent = client.send('my name is QuecPython\r\n')
    client.logger.info('send {} bytes'.format(bytes_sent))
    
    # 接收响应
    data = client.recv(256)
    client.logger.info('recv {} bytes'.format(len(data)))
    client.logger.info(data.decode())
    
    # 关闭连接
    client.close()

